//
//  XMPPDBManager.m
//  Messenger
//
//  Created by OC on 15/1/15.
//  Copyright (c) 2015年 李健. All rights reserved.
//
//  数据库管理类
//

#import "XMPPDBManager.h"
#import "YNUserTreeRelation.h"
#import "YNContactGroupRelation.h"
#import "YNIMFrameworkMacro.h"
#import "YNOrgTree.h"
#import "YNUser.h"
#import "YNContactGroup.h"
#import "YNRecentChatObejct.h"
#import "YNTwoPeopleChat.h"
#import "YNManyPeopleChat.h"
#import "YNBroadcastChat.h"
#import "RemindSet.h"
#import "MessageRemind.h"
#import "YNIMmanager.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"

@interface XMPPDBManager()
{
    FMDatabaseQueue *_queue;
}
@end

@implementation XMPPDBManager

+ (XMPPDBManager *)sharedInstance
{
    static dispatch_once_t onceToken;
    static XMPPDBManager *sharedDBQueueManager = nil;
    dispatch_once(&onceToken, ^{
        sharedDBQueueManager = [[XMPPDBManager alloc] init];
    });
    return sharedDBQueueManager;
}
///创建FMDatabaseQueue
-(void)creatDatabaseQueueWithPath:(NSString*)dbPath{
    _queue = nil;
    _queue = [FMDatabaseQueue databaseQueueWithPath:dbPath];
}

- (void)dealloc
{
    _queue = nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

-(FMDatabaseQueue *)achieveQueue
{
    FMDatabaseQueue *queue = (FMDatabaseQueue *)[self createTable:YES];
    
    return queue;
}

- (id)createTable:(BOOL)isQueue
{
    WEAKSELF
    dispatch_semaphore_t createTableSemaphore = dispatch_semaphore_create(0);
    [_queue inDatabase:^(FMDatabase *db) {

        [weakSelf createContactTableInDatabase:db];
        
        dispatch_semaphore_signal(createTableSemaphore);
        
    }];
    
    dispatch_semaphore_wait(createTableSemaphore, DISPATCH_TIME_FOREVER);
    
    if(isQueue)
    {
        return _queue;
    }
    return nil;
}

- (void)createContactTableInDatabase:(FMDatabase *)db
{
    [YNOrgTree createInDatabase:db];
    [YNUser createInDatabase:db];
    [YNUserTreeRelation createInDatabase:db];
    [YNContactGroup createDatabase:db];
    [YNContactGroupRelation createWithGroupDatabase:db];
    [YNRecentChatObejct createRecentChatTableInDatabase:db];
    [YNTwoPeopleChat creatTwoPeopleChatTableInDatabase:db];
    [YNManyPeopleChat creatManyPeopleChatWithGroupType:kContact_UserGroupType inDatabase:db];
    [YNManyPeopleChat creatManyPeopleChatWithGroupType:kContact_DiscussionGropType inDatabase:db];
    [YNManyPeopleChat creatManyPeopleChatWithGroupType:kContact_ProjectTeamGropType inDatabase:db];
    [YNBroadcastChat creatBroadcastMesageTableInDatabase:db];
    [RemindSet createInDatabase:db];
    [MessageRemind createInDatabase:db];
}



@end
